import Node from '../core/Node';

export default class Sector extends Node {
  static TYPE = {
    STROKE: 1,
    FILL: 2,
  }

  constructor(canvas, style) {
    super(canvas, style);
    this.startAngle = style.startAngle || 0;
    this.endAngle = style.endAngle || 360;
    this.radiusLen = style.radius || '3px';
    this.type = style.type || Sector.TYPE.STROKE;
  }

  get radius() {
    return this.getRelativePixel(this.radiusLen);
  }


  draw(painter) {
    if (this.type === Sector.TYPE.STROKE) {
      painter.strokeStyle = this.color;
      painter.lineWidth = this.lineWidth;
    } else {
      painter.fillStyle = this.color;
    }
    // 设置渐变色
    if (this.linearGradient.length > 0) {
      const lingrad = painter.createRadialGradient(
        this.left,
        this.bottom,
        0,
        this.left,
        this.bottom,
        this.radius,
      );
      for (let i = 0; i < this.linearGradient.length; i++) {
        lingrad.addColorStop(this.linearGradient[i][0], this.linearGradient[i][1]);
      }
      if (this.type === Sector.TYPE.STROKE) {
        painter.strokeStyle = lingrad;
      } else {
        painter.fillStyle = lingrad;
      }
    }
    painter.beginPath();
    painter.arc(
      this.left / this.scaleX,
      this.bottom / this.scaleY,
      this.radius,
      this.startAngle / 180 * Math.PI,
      this.endAngle / 180 * Math.PI,
    );
    painter.lineTo(
      this.left / this.scaleX,
      this.bottom / this.scaleY
    );
    painter.closePath();
    if (this.type === Sector.TYPE.STROKE) {
      painter.stroke();
    } else {
      painter.fill();
    }
  }

  containsPoint(_p) {
    const dist = (_p.x - this.left) * (_p.x - this.left)
      + (_p.y - this.bottom) * (_p.y - this.bottom);
    if (dist > this.radius * this.radius) {
      return false;
    }
    const tan = -(_p.y - this.bottom) / (_p.x - this.left);
    let atan = Math.atan(tan);
    if (_p.x < this.left && _p.y < this.bottom) {
      atan = Math.PI + atan;
    } else if (_p.x < this.left && _p.y > this.bottom) {
      atan = Math.PI * 3 / 2 + atan;
    } else if (_p.x > this.left && _p.y > this.bottom) {
      atan = Math.PI * 2 + atan;
    }
    if (this.endAngle < this.startAngle) {
      return atan >= this.startAngle / 180 * Math.PI || atan <= this.endAngle / 180 * Math.PI;
    } else {
      return atan >= this.startAngle / 180 * Math.PI && atan <= this.endAngle / 180 * Math.PI;
    }
  }
}
